package Service;

import Dao.Impl.UserDAOImpl;
import Dao.Impl.VerificationCodeDAOImpl;
import Dao.VerificationCodeDAO;
import entity.VerificationCode;
import utils.DBUtil;
import utils.EmailUtil;
import utils.VerificationCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Su
 * @Date 2025/5/1 17:20
 * @Version 1.0 （版本号）
 */
public class EmailService {

    private VerificationCodeDAO verificationCodeDAO;

    public EmailService(Connection connection) {
        this.verificationCodeDAO = new VerificationCodeDAOImpl(connection);
    }


    public Map<String, Object> codeGenAndSend(String email,String type) throws SQLException {
        // 生成验证码
        String code = VerificationCodeUtil.generateCode();
        Date expireTime = VerificationCodeUtil.getExpireTime();

        // 保存到数据库
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setEmail(email);
        verificationCode.setCode(code);
        verificationCode.setType(type);
        verificationCode.setExpireTime(expireTime);

        boolean saved = verificationCodeDAO.insertCode(verificationCode);
        Map<String, Object> response = new HashMap<>();
        if (saved) {
            // 发送邮件
            boolean sent = EmailUtil.sendVerificationCode(email, code);
            if (sent) {
                response.put("code", 200);
                response.put("message", "验证码已发送");
            } else {
                response.put("code", 400);
                response.put("message", "验证码发送失败");
            }
        } else {
            response.put("code", 500);
            response.put("message", "系统错误，请重试");
        }
        return response;
    }
}
